package com.neusoft.elmboot.controller;


import com.neusoft.elmboot.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传的控制器
 */
@RestController
public class FileUploadController {

    @Value("${project.file.storage.form}")
    private String storageForm;

    @Value("${project.file.storage.path}")
    private String storagePath;


    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            return Result.fail(500,"上传文件不能为空！");
        }
        String originalFilename = file.getOriginalFilename();
        System.out.println("----文件名："+originalFilename);
        System.out.println("-----storageForm:"+storageForm);
        System.out.println("-----storagePath:"+storagePath);

        byte[] bytes = file.getBytes(); // 文件的二进制的字节数组。


        String url = "";
        if("file".equals(storageForm.trim())) {
            // 获取文件的真实路径，并保存文件
            String uploadDirectory = System.getProperty("user.dir") + "/upload/";
            File dir = new File(uploadDirectory);
            // 如果文件上传的目录不存在，则：创建该目录！
            if (!dir.exists()) {
                dir.mkdirs();
            }
            File destinationFile = new File(uploadDirectory, file.getOriginalFilename());
            file.transferTo(destinationFile);
            System.out.println("文件上传成功：" + destinationFile.getAbsolutePath());
            url = "/upload/"+destinationFile.getName();
        }


        if("db".equals(storageForm.trim())) {
            // 注意：如果使用Base64转图片为字符串，需保证图片足够小！
            String base64String = Base64.getEncoder().encodeToString(bytes);
            System.out.println("--------上传成功，内容为：");
            String base64Header = "data:image/png;base64,";
            url = base64Header + base64String;

        }
        System.out.printf("......url:\n%s\n",url);
        Map<String,Object> retMap = new HashMap<>();
        retMap.put("url",url);
        return Result.success(retMap,"上传成功");
    }

}
